package com.xyauto.theme.utils

import android.content.Intent
import android.content.pm.PackageManager
import android.os.SystemProperties
import android.provider.Settings
import android.text.TextUtils
import com.blankj.utilcode.util.LogUtils
import com.google.gson.Gson
import com.google.gson.stream.JsonReader
import com.tencent.mmkv.MMKV
import com.xyauto.theme.App
import com.xyauto.theme.BuildConfig
import kotlinx.coroutines.*
import java.io.File
import java.io.FileReader


object SelectManager {


    private const val KEY_MMKV_SELECT = "com.xyauto.theme.mmkv.selectBean"

    private const val KEY_SYSTEM_PROPERTIES_TYPE: String = "start_new_launcher"
    private const val KEY_SETTING_SELECT_NAME: String = "com.xyauto.theme.selectName"
    private const val KEY_SETTING_SELECT_TEMP_NAME: String = "com.xyauto.theme.temp.selectName"

    private const val KEY_SETTING_JMY_INDEX: String = "xy.launcher.ui.index"
    private const val KEY_SETTING_JMY_WP_INDEX: String = "xy.launcher.ui.wpindex"

    private const val TYPE_SELECT_NULL = -1
    private const val TYPE_SELECT_LAUNCHER = 1
    private const val TYPE_SELECT_JMY = 0


    private lateinit var selectTheme: SelectBean

    /**
     * 读取选中
    [KEY_MMKV_SELECT]=Json{type:Int,name:String,index:Int} 第1条，优先级最高，有此项不读取其他缓存

    [KEY_SYSTEM_PROPERTIES_TYPE]:SystemProperties参数 第2条件,与系统公用，若不存在判断第3条件

    [com.android.launcher]:包名 第3条件,检测当前启动launcher包名，如果成立读取第4条件，否则视为[TYPE_SELECT_JMY]

    [BuildConfig.DEFAULT_CONFIG_PATH]:String?  第4条件，读取配launcher的配置文件视为[TYPE_SELECT_LAUNCHER],若不存在判断第5条件

    [KEY_SETTING_JMY_INDEX]:Int(-1~999) 第5条件，以上条件都不满足时读取此条件视为[TYPE_SELECT_JMY] 否则进入error状态，即无选中状态
     */
    fun init() {
        CoroutineScope(Dispatchers.IO).launch {
            selectTheme = MMKV.defaultMMKV()?.decodeString(KEY_MMKV_SELECT)?.toBean(SelectBean::class.java) ?: SelectBean().apply {
                val jmyIndex = Settings.System.getInt(App.instance.contentResolver, KEY_SETTING_JMY_INDEX, -1)
                val typeVar = loadType()
                if (typeVar == TYPE_SELECT_JMY) {
                    type = typeVar
                    index = jmyIndex
                } else {
                    val selectName = Settings.Global.getString(App.instance.contentResolver, KEY_SETTING_SELECT_NAME)
                    if (!TextUtils.isEmpty(selectName)) {
                        type = TYPE_SELECT_LAUNCHER
                        nameAndPath = selectName
                    } else {
                        val defThemeName = loadLauncherConfig()
                        if (!defThemeName.isNullOrEmpty()) {
                            type = TYPE_SELECT_LAUNCHER
                            nameAndPath = defThemeName
                        } else if (jmyIndex != -1) {
                            type = TYPE_SELECT_JMY
                            index = jmyIndex
                        } else {
                            type = TYPE_SELECT_NULL
                            index = jmyIndex
                        }
                    }
                }
            }
            LogUtils.i("init: $selectTheme")
            saveSelect(selectTheme)
        }
    }


    private fun loadType(): Int {
        var typeVar = SystemProperties.getInt(KEY_SYSTEM_PROPERTIES_TYPE, TYPE_SELECT_NULL)
        if (typeVar == TYPE_SELECT_NULL) {
            val intent = Intent("android.intent.action.MAIN")
            intent.addCategory("android.intent.category.HOME")
            val launcherPackageName = App.instance.packageManager
                .resolveActivity(intent, PackageManager.MATCH_DEFAULT_ONLY)?.activityInfo?.packageName ?: ""
            LogUtils.i("init launcherPackageName= $launcherPackageName")
            typeVar = if (TextUtils.equals(launcherPackageName, "com.android.launcher")) {
                TYPE_SELECT_LAUNCHER
            } else {
                TYPE_SELECT_JMY
            }
        }
        return typeVar
    }

    fun isSelectTheme(nameOrIndex: Any): Boolean = when {
        nameOrIndex is Int && selectTheme.type == TYPE_SELECT_JMY -> selectTheme.index == nameOrIndex
        nameOrIndex is String && selectTheme.type == TYPE_SELECT_LAUNCHER -> selectTheme.name == nameOrIndex
        else -> false
    }

    fun setSelectTheme(nameOrIndex: Any) {
        when (nameOrIndex) {
            is Int -> saveSelect(selectTheme.apply {
                type = TYPE_SELECT_JMY
                index = nameOrIndex
                nameAndPath = ""
            })
            is String -> saveSelect(selectTheme.apply {
                type = TYPE_SELECT_LAUNCHER
                nameAndPath = nameOrIndex
                index = -1
            })
        }
    }


    private fun saveSelect(bean: SelectBean) {
        //MMKV.defaultMMKV()?.encode(KEY_MMKV_SELECT, bean.toJson())
        SystemProperties.set(KEY_SYSTEM_PROPERTIES_TYPE, "${bean.type}")
        //Settings.System.putInt(App.instance.contentResolver, KEY_SETTING_SELECT_TYPE, bean.type)
        AtcMetaZoneTools.writereserved_offset(bean.type,AtcMetaZoneTools.KEY_SELECT_TYPE,1)

        Settings.Global.putString(App.instance.contentResolver, KEY_SETTING_SELECT_NAME, bean.nameAndPath)
        //防止launcher丢失广播时无法切换到对应主题
        Settings.Global.putString(App.instance.contentResolver, KEY_SETTING_SELECT_TEMP_NAME, bean.nameAndPath)

        val index = bean.index
        /*if (index < 0 && JieMainYiManager.themeCount > 0) {
            index = JieMainYiManager.themeCount
        }*/
        if (index >= 0) {
            JieMainYiManager.saveSelectData(index)
            Settings.System.putInt(App.instance.contentResolver, KEY_SETTING_JMY_INDEX, index)
            Settings.System.putInt(App.instance.contentResolver, KEY_SETTING_JMY_WP_INDEX, index)
        }
    }


    /*Launcher默认桌面类型*/
    private data class DefConfigBean(val theme_name: String?)

    private data class SelectBean(var type: Int = TYPE_SELECT_NULL, var index: Int = -1) {
        var nameAndPath: String = ""
            set(value) {
                field = value
                name = null
            }
        var name: String? = null
            get() {
                if (field.isNullOrBlank()) {
                    field = if (nameAndPath.contains("&&")) {
                        nameAndPath.split("&&")[0]
                    } else {
                        nameAndPath
                    }
                }
                return field
            }
    }


    private fun loadLauncherConfig() = File(BuildConfig.DEFAULT_CONFIG_PATH).let {
        if (it.exists()) {
            Gson().fromJson<DefConfigBean>(JsonReader(FileReader(it)), DefConfigBean::class.java)?.theme_name
        } else {
            null
        }
    }
}